package com.xpgk.sbwx.login;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;

import com.jfinal.log.Log;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantLogin;
import com.xpgk.constant.ConstantRender;
import com.xpgk.interceptor.AuthInterceptor;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.user.User;
import com.xpgk.tools.security.ToolPbkdf2;

@Service(name = WXLoginService.serviceName)
public class WXLoginService extends BaseService {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(WXLoginService.class);

	public static final String serviceName = "loginService";

	/**
	 * 用户登录后台验证
	 * 
	 * @param request
	 * @param response
	 * @param userName
	 *            账号
	 * @param passWord
	 *            密码
	 * @param autoLogin
	 *            是否自动登录
	 * @return
	 */
	public String login(HttpServletRequest request, HttpServletResponse response, String userName, String passWord,
			boolean autoLogin) {
		// 1.取用户
		User user = User.cacheGetByUserName(userName);
		if (null == user) {
			return "用户不存在！";// 用户不存在
		}

		// 2.停用账户
		String status = user.getStr(User.column_status);
		if (status.equals("0")) {
			return "账号已停用！";
		}

		// 3.验证密码
		String saltStr = user.get(User.column_salt); // 密码盐
		byte[] salt = Base64.decodeBase64(saltStr);
		String passStr = user.get(User.column_password); // 密码
		byte[] encryptedPassword = Base64.decodeBase64(passStr);
		boolean bool = false;
		try {
			bool = ToolPbkdf2.authenticate(passWord, encryptedPassword, salt);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}
		if (bool) {
			// 密码验证成功
			AuthInterceptor.setCurrentUser(request, response, user, autoLogin);// 设置登录账户
			return ConstantRender.render_success_code;
		} else {
			return "密码错误！";
		}
	}
}
